import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

import 'package:latlong2/latlong.dart';
import '../../helper/Helper.dart';
import '../../helper/channelHelper.dart';
import '../../helper/uidata.dart';
import '../../model/inspectreport.dart';
import '../../pages/gmap/gmap.dart';
import '../../pages/gmap/gmapHelper.dart';
import '../../pages/gmap/gpsHelper.dart';
import '../../spaces/recordspace/record_list.dart';
import '../../widgets/dialogWidget.dart';
import 'package:wakelock/wakelock.dart';

import 'InspectCard.dart';
import 'inspectReport_list.dart';

class InspectReportAddPage extends StatefulWidget {
  @override
  InspectReportAddPage(this.added, this.zone1, this.type1);
  final InspectAddCallback added;
  final String zone1;
  final String type1;

  @override
  InspectReportAddPageState createState() => InspectReportAddPageState();
}

class InspectReportAddPageState extends State<InspectReportAddPage> {
  late InspectReport X1;
  late List<LatLng> gpsList;
  late LatLng location;
  bool IfRemarkGPS = true;
  double distance = 0.0;
  double tmLast = 0.0;
  int currentPage = 0;
  bool ifLoaded = false;
  bool ifBegin = false;
  bool ifLocation = false;

  final TextEditingController c1 = TextEditingController();
  @override
  void initState() {
    // TODO: implement initState

    super.initState();
    beginGo();
    //RiverItem river = CacheHelper.GetRiverItem(X1.RiverItemId);
  }

  bool ifCarryOn() {
    if (Helper.localDB.containsKey("InspectGuid")) {
      var sjc = getTMFZ();
      if (sjc > 30) {
        return false;
      } else {
        return true;
      }
    }
    return false;
  }

  int getTMFZ() {
    var bTm = DateTime.tryParse(Helper.localDB.getString("InspectTM")!);
    if (bTm == null) return 0;
    var now = DateTime.now();
    var sjc = now.difference(bTm).inMinutes;
    return sjc;
  }

  void beginGo() async {
    String guid;
    String bTm;
    //  await Helper.localDB.remove("InspectGuid");
    Wakelock.enable();
    location = LatLng(42.0, 123.0);
    ifBegin = ifCarryOn();

    if (ifBegin) {
      guid = Helper.localDB.getString("InspectGuid")!;
      bTm = Helper.localDB.getString("InspectTM")!;
      gpsList = GpsHelper.StringToPointList(
          Helper.localDB.getString("InspectGpsStr")!);
      distance = Helper.localDB.getDouble("InspectDistance")!;
      //  print(riverId);
      beginGo3(guid, bTm);
      //tmLast=Helper.localDB.getDouble("InspectTimeLast");
    } else {
      beginGo2();
    }
  }

  void beginGo2() {
    var guid = Helper.GetGuid();
    var bTm = Helper.DateTimeNowString();
    gpsList = <LatLng>[];
    beginGo3(guid, bTm);
  }

  void beginGo3(String guid1, String bTM1) async {
    X1 = InspectReport(
        0,
        guid1,
        widget.zone1,
        UIData.CurrentUser!.Guid,
        bTM1,
        "",
        widget.type1,
        bTM1,
        0,
        "",
        "",
        "",
        "",
        distance,
        tmLast,
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "",
        "");
    getLocation();

    setState(() {
      ifLoaded = true;
    });
  }

  void onData(dynamic data) {
    var st = data.toString();
    print(st);
    var loc2 = GMapHelper.getLocation(st);
    //var loc3 = GpsHelper.transform(loc2.latitude, loc2.longitude);
    //var loc2 = GpsHelper.transform(loc1.latitude, loc1.longitude);

    setState(() {
      location.latitude = loc2.latitude;
      location.longitude = loc2.longitude;

      if (gpsList.length > 0)
        distance += GpsHelper.getDistance(gpsList.last.latitude,
            gpsList.last.longitude, loc2.latitude, loc2.longitude);
    });
    gpsList.add(loc2);

    var gpsStr = GpsHelper.PointListToString(gpsList);
    var sjc = getTMFZ();

    if (sjc < 10) tmLast += sjc * 1.0;

    Helper.localDB.setString("InspectDataTM", Helper.DateTimeNowString());
    Helper.localDB.setString("InspectGpsStr", gpsStr);
    Helper.localDB.setDouble("InspectDistance", distance);
    Helper.localDB.setDouble("InspectTimeLast", tmLast);
  }

  Future getLocation() async {
    if (ifLocation) return;
    ifLocation = true;
    await Helper.CheckLocationPersmission();
    ChannelHelper.LocationChannel.receiveBroadcastStream().listen(onData);
  }

  upload(BuildContext context) async {
    X1.Bz1 = c1.text;
    X1.EndTM = Helper.DateTimeNowString();
    X1.Distance = distance;
    X1.GpsRemark = GpsHelper.PointListToString(gpsList);
    X1.MinutesLast = Helper.DateTimeByNow(X1.CreateTM).toDouble();

    var pb1 = await InspectReport.Add(X1);

    Wakelock.disable();
    if (pb1 == true) {
      InspectReport.Update(X1);
      await Helper.localDB.remove("InspectGuid");
      if (widget.added != null) widget.added(X1);
      Navigator.of(context).pop();
    }
  }

  delete(BuildContext context) async {
    await Helper.localDB.remove("InspectGuid");
    Wakelock.disable();
    if (widget.added != null) widget.added(X1);
    Navigator.of(context).pop();
  }

  _ifCanDelete() {
    return true;
  }

  //  定义底部导航列表
  List<BottomNavigationBarItem> bottomTabs = [
    new BottomNavigationBarItem(icon: new Icon(Icons.book), label: ('基础信息')),
    new BottomNavigationBarItem(icon: new Icon(Icons.map), label: ('巡查路线')),
    new BottomNavigationBarItem(
        icon: new Icon(Icons.camera_alt), label: ('巡查记录')),
    // new BottomNavigationBarItem(
    //     icon: new Icon(Icons.list), label:('问题上报')),
  ];

  Widget getBody(int x) {
    if (x == 0) return inspectReportAddBody(context);
    if (x == 1)
      return MyMap(
        location: GpsHelper.transformP(location),
        layers: _mapLayers(location),
        zoom: 16.0,
      );

    // var sX= SpaceX.NewX(X1.Guid, UIData.appGuid, "库区巡查");
    if (x == 2) return RecordListPage(X1.Guid, true);
    return Container();
  }

  List<LayerOptions> _mapLayers(LatLng p1) {
    var layers = GMapHelper.NewLayerList();
    layers.add(GMapHelper.PolylineLayer(
        GpsHelper.transformPList(gpsList), 2.0, Colors.red));
    layers.add(GMapHelper.MyLocation(GpsHelper.transformP(location)));
    return layers;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("库区巡查"),
      ),

      bottomNavigationBar: new BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          currentIndex: currentPage,
          items: bottomTabs,
          fixedColor: Colors.blue,
          onTap: (index) {
            setState(() {
              currentPage = index;
            });
          }),
      // body:currentPage==0? InspectReportAddBody(context):RecordListPage(X1.Guid,true,_ifCanDelete()),
      body: ifLoaded
          ? getBody(currentPage)
          : Center(
              child: SpinKitCircle(
              color: Colors.blue,
            )),
    );
  }

  inspectReportAddBody(BuildContext context) {
    //print(X1.RiverItemId);
    return SingleChildScrollView(
      child: AllBody(context),
    );
  }

  Widget BodyHeader(BuildContext context) {
    return Card(
      child: Column(children: <Widget>[
        Container(
            height: 48.0,
            child: Center(
                child: Text(
              "正在巡库...",
              style: TextStyle(fontSize: 16.0, color: Colors.red),
            ))),
        Divider(
          height: 0.0,
        ),
        ListTile(
          title: Text("巡查库段"),
          // trailing: rItem == null ? Text("") : Text(rItem.Name),
        ),
        Divider(
          height: 0.0,
        ),
        ListTile(
          title: Text("开始时间"),
          trailing: Text(X1.CreateTM),
        ),
        Divider(
          height: 0.0,
        ),
        ListTile(
          title: Text("巡查时间"),
          trailing: Text("${Helper.DateTimeByNow(X1.CreateTM)} 分钟"),
        ),
        Divider(
          height: 0.0,
        ),
        ListTile(
          title: Text("巡查里程"),
          trailing: Text("${distance.toStringAsFixed(0)} 米"),
        ),
      ]),
      // color: GlobalConfig.cardBackgroundColor,
      margin: const EdgeInsets.all(6.0),
    );
  }

  newInspect() async {
    Helper.localDB.setString("InspectGuid", X1.Guid);
    Helper.localDB.setString("InspectTM", X1.CreateTM);
    Helper.localDB.setDouble("InspectDistance", 0);
    Helper.localDB.setString("InspectGpsStr", "");
    Helper.localDB.setString("InspectRiverItemId", "");
    Helper.localDB.setString("InspectTimeLast", "");
    setState(() {
      ifBegin = true;

      getLocation();
    });
  }

  Widget AllBody(BuildContext context) {
    if (!ifBegin) {
      return Column(children: <Widget>[
        Container(
          height: 60.0,
          margin: EdgeInsets.only(top: 60),
        ),
        InspectCard.inspectButton(context, "开始巡库", "开始巡库", newInspect, mt1: 120)
      ]);
    }
    return Container(
      margin: EdgeInsets.only(top: 8.0, bottom: 12.0),
      child: Column(children: <Widget>[
        BodyHeader(context),
        InspectReportAddFields(context),
      ]),
    );
  }

  InspectReportAddFields(BuildContext context) {
    return Container(
        child: Column(children: <Widget>[
      Card(
        child: (ListTile(
          title: Center(child: Text("放弃本次巡库")),
          onTap: () {
            DialogWidget.ShowUpload(context, "放弃本次巡库", () => delete(context));
            //delete(context);
          },
        )),
        // color: GlobalConfig.cardBackgroundColor,
        margin: const EdgeInsets.all(6.0),
      ),
      InspectCard.inspectButton(
          context, "完成巡库并上报", "提交上传巡库记录", () => upload(context)),
    ]));
  }
}
